//
//  TextConvertible.swift
//  
//
//  Created by 张泽群 on 2022/8/9.
//

import UIKit

public protocol TextConvertible {
    /// 是否是富文本
    var isAttributesText: Bool { get }

    func isEquate(_ text: String) -> Bool
}

extension TextConvertible {
    func widthForFont(_ font: UIFont, height: CGFloat) -> CGFloat {
        if isAttributesText {
            return (self as! NSAttributedString).width(of: height)
        } else {
            return (self as! String).widthForFont(font, height: height)
        }
    }
}

extension String {
    func widthForFont(_ font: UIFont, height: CGFloat) -> CGFloat {
        let size = CGSize(width: CGFloat.greatestFiniteMagnitude, height: height)
        let text = self as NSString
        let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
        let rect =  text.boundingRect(with: size, options: options, attributes: [.font: font], context: nil)
        return ceil(rect.size.width)
    }
}

extension NSAttributedString {
    func width(of height: CGFloat) -> CGFloat {
        let size = CGSize(width: CGFloat.greatestFiniteMagnitude, height: height)
        return ceil(boundingRect(with: size, context: nil).width)
    }
}

extension String: TextConvertible {
    public var isAttributesText: Bool {
        return false
    }

    public func isEquate(_ text: String) -> Bool {
        return self == text
    }
}

extension NSAttributedString: TextConvertible {
    public var isAttributesText: Bool {
        return true
    }

    public func isEquate(_ text: String) -> Bool {
        return string == text
    }
}
